<template>
    <div class="live2d-ai-assistant">
        <!-- 与看板娘关联的聊天窗口 -->
        <div class="pio-chat-container" :class="{ active: chatActive }">
            <div class="chat-header">
                <div class="chat-title">
                    <i class="el-icon-chat-dot-round"></i>
                    <span>茶叶智能助手</span>
                </div>
                <i class="el-icon-close close-btn" @click="toggleChat(false)"></i>
            </div>
            <div class="chat-messages" ref="messageContainer">
                <div v-for="(message, index) in messages" :key="index"
                    :class="['message', message.type === 'user' ? 'user-message' : 'ai-message']">
                    <div class="message-content">
                        <!-- 思考区域显示 -->
                        <div v-if="parseContent(message).think" class="thinking-content">
                            <div class="thinking-text" v-html="renderMarkdown(parseContent(message).think)"></div>
                        </div>

                        <!-- 消息内容，使用parse方法获取纯回答内容 -->
                        <div class="message-text" v-html="renderMarkdown(message.type === 'ai' ? parseContent(message).answer : message.content)"></div>

                        <!-- 引用信息显示 (只在AI消息中显示) -->
                        <div class="citations-container"
                            v-if="message.type === 'ai' && message.citations && message.citations.length > 0">
                            <div class="citations-header" @click="toggleCitations(index)">
                                <i :class="['el-icon-arrow-right', { 'rotated': message.showCitations }]"></i>
                                <span>查看引用来源 ({{ message.citations.length }})</span>
                            </div>
                            <div class="citations-list" v-if="message.showCitations">
                                <el-card v-for="(citation, citIndex) in message.citations" :key="citIndex"
                                    class="citation-item" shadow="hover">
                                    <div class="citation-source">
                                        <i
                                            :class="citation.source === '网络搜索' || citation.source.includes('网') ? 'el-icon-search' : 'el-icon-document'"></i>
                                        <span>{{ citation.source || '本地知识库' }}</span>
                                    </div>
                                    <div class="citation-title">{{ citation.title !== '未知标题' ? citation.title : '本地知识库'
                                        }}</div>
                                    <div class="citation-text" v-if="citation.text">{{ citation.text }}</div>
                                    <div class="citation-snippet" v-if="citation.snippet">{{ citation.snippet }}</div>
                                    <div class="citation-url" v-if="citation.url">
                                        <a :href="citation.url" target="_blank">{{ citation.url }}</a>
                                    </div>
                                </el-card>
                            </div>
                        </div>

                        <div class="message-time" v-if="message.time">{{ message.time }}</div>
                    </div>
                </div>

                <!-- 思考状态显示 - 只在处理请求且还没有收到响应时显示 -->
                <div class="thinking-indicator" v-if="isThinking">
                    <div class="thinking-dots">
                        <span></span>
                        <span></span>
                        <span></span>
                    </div>
                    <div class="thinking-text">{{ thinkingText }}</div>
                </div>
            </div>
            <div class="chat-input-area">
                <div class="chat-input">
                    <el-input v-model="userInput" type="textarea" :rows="1" autosize resize="none"
                        placeholder="请输入您的问题..." @keyup.enter.native="handleEnterPress"></el-input>
                    <button class="send-btn" @click="sendMessage" :disabled="isProcessing || !userInput.trim()"
                        :class="{ 'sending': isProcessing }">
                        <i v-if="!isProcessing" class="el-icon-position"></i>
                        <i v-else class="el-icon-loading"></i>
                    </button>
                </div>
                <div class="chat-tools">
                    <div class="tool-btn knowledge-base" @click="toggleKnowledgeBase"
                        :class="{ 'active': knowledgeBase }">
                        <i class="el-icon-document"></i>
                        <span>知识库</span>
                    </div>
                    <div class="tool-btn web-search" @click="toggleOnline" :class="{ 'active': online }">
                        <i class="el-icon-search"></i>
                        <span>联网搜索</span>
                    </div>
                    <div class="tool-btn citation" @click="toggleCitation" :class="{ 'active': citation }"
                        :disabled="!canEnableCitation">
                        <i class="el-icon-collection"></i>
                        <span>引用模块</span>
                    </div>
                    <div class="tool-btn deepseek" @click="toggleDeepseek" :class="{ 'active': useDeepseek }">
                        <i class="el-icon-cpu"></i>
                        <span>DeepSeek</span>
                    </div>
                    <div class="tool-btn cancel" v-if="isProcessing" @click="cancelGeneration">
                        <i class="el-icon-close"></i>
                        <span>取消生成</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import aiService from '../api/aiService';
import router from '../router';
import MarkdownIt from 'markdown-it';
import mk from 'markdown-it-katex';
import 'katex/dist/katex.min.css';

// 初始化Markdown渲染器
const md = new MarkdownIt({ html: true, linkify: true, breaks: true }).use(mk);

// 重写streamQuestion和streamWithCitation方法
const originalStreamQuestion = aiService.streamQuestion;
const originalStreamWithCitation = aiService.streamWithCitation;

// 使用fetch API代替EventSource来处理POST请求 - 普通流式接口
aiService.streamQuestion = function (question, slug = 'test', online = false, knowledgeBase = false, userId = '1', onData, onError, onComplete) {
    const controller = new AbortController();
    const { signal } = controller;

    // 准备请求体数据 - 不需要citation参数
    const data = {
        question,
        online,
        knowledge_base: knowledgeBase,
        user_id: userId
    };

    // 使用fetch API发送POST请求
    fetch(`${aiService.baseURL || 'http://localhost:8001'}/workspace/${slug}/chat/stream`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
        signal
    })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            // 获取响应的reader
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let buffer = '';

            // 读取数据流
            function readStream() {
                reader.read().then(({ done, value }) => {
                    if (done) {
                        if (onComplete) onComplete();
                        return;
                    }

                    // 解码数据
                    const chunk = decoder.decode(value, { stream: true });
                    buffer += chunk;

                    // 处理数据行
                    const lines = buffer.split('\n\n');
                    buffer = lines.pop() || '';

                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            const data = line.substring(6);
                            if (data === '[DONE]') {
                                if (onComplete) onComplete();
                                return;
                            }

                            try {
                                const parsedData = JSON.parse(data);
                                if (onData) onData(parsedData);
                            } catch (e) {
                                console.error('Error parsing stream data:', e);
                            }
                        }
                    }

                    // 继续读取
                    readStream();
                }).catch(error => {
                    if (error.name !== 'AbortError') {
                        console.error('Stream error:', error);
                        if (onError) onError(error);
                    }
                });
            }

            // 开始读取
            readStream();
        })
        .catch(error => {
            if (error.name !== 'AbortError') {
                console.error('Fetch error:', error);
                if (onError) onError(error);
            }
        });

    // 返回控制器以便外部可以中断请求
    return {
        close: () => controller.abort()
    };
};

// 同样修改streamWithCitation方法
aiService.streamWithCitation = function (question, slug = 'test', online = false, knowledgeBase = false, userId = '1', onData, onError, onComplete) {
    const controller = new AbortController();
    const { signal } = controller;

    // 准备请求体数据 - 使用专门的引用接口，不需要发送citation参数
    const data = {
        question,
        online,
        knowledge_base: knowledgeBase,
        user_id: userId
    };

    // 使用专门的引用API接口
    fetch(`${aiService.baseURL || 'http://localhost:8001'}/workspace/${slug}/chat/citation/stream`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
        signal
    })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            // 获取响应的reader
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let buffer = '';

            // 读取数据流
            function readStream() {
                reader.read().then(({ done, value }) => {
                    if (done) {
                        if (onComplete) onComplete();
                        return;
                    }

                    // 解码数据
                    const chunk = decoder.decode(value, { stream: true });
                    buffer += chunk;

                    // 处理数据行
                    const lines = buffer.split('\n\n');
                    buffer = lines.pop() || '';

                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            const data = line.substring(6);
                            if (data === '[DONE]') {
                                if (onComplete) onComplete();
                                return;
                            }

                            try {
                                const parsedData = JSON.parse(data);
                                if (onData) onData(parsedData);
                            } catch (e) {
                                console.error('Error parsing stream data:', e);
                            }
                        }
                    }

                    // 继续读取
                    readStream();
                }).catch(error => {
                    if (error.name !== 'AbortError') {
                        console.error('Stream error:', error);
                        if (onError) onError(error);
                    }
                });
            }

            // 开始读取
            readStream();
        })
        .catch(error => {
            if (error.name !== 'AbortError') {
                console.error('Fetch error:', error);
                if (onError) onError(error);
            }
        });

    // 返回控制器以便外部可以中断请求
    return {
        close: () => controller.abort()
    };
};

export default {
    name: 'Live2dAIAssistant',
    data() {
        return {
            pioInstance: null, // 保存看板娘实例
            chatActive: false, // 控制聊天窗口显示
            userInput: '', // 用户输入
            messages: [
                {
                    type: 'ai',
                    content: '茶友你好！我是智能茶叶助手-小茶，有什么可以帮您的吗？',
                    time: this.formatTime(new Date())
                }
            ],
            isProcessing: false, // 是否正在处理请求
            originalRenderFunction: null, // 保存看板娘原始的render函数
            originalHomeFunction: null, // 保存看板娘原始的home按钮函数
            isAIMessage: false, // 标志是否正在处理AI消息
            webSearchActive: false, // 联网搜索状态
            isThinking: false, // 思考状态
            thinkingText: '正在思考中...', // 思考文本
            currentEventSource: null, // 当前流式请求
            userId: '1', // 用户ID，实际应从用户系统获取
            knowledgeBase: false, // 是否使用知识库
            knowledgeBaseSlug: 'test', // 知识库slug，默认使用test
            streamBuffer: '', // 流式输出缓冲
            thinkingBuffer: '', // 思考内容缓冲
            inThinkingMode: false, // 是否在思考模式
            citations: [], // 引用信息
            online: false,
            citation: false,
            useDeepseek: false, // 是否使用deepseek模型
        }
    },
    computed: {
        canEnableCitation() {
            return this.knowledgeBase || this.online;
        }
    },
    mounted() {
        // 尝试获取全局的pio_instance
        this.initPioInstance();

        // 监听窗口大小变化，调整聊天窗口位置
        window.addEventListener('resize', this.adjustChatPosition);
    },
    methods: {
        // 解析消息内容，提取思考部分和回答部分
        parseContent(message) {
            if (message.type !== 'ai') return { think: null, answer: message.content };
            
            // 检查是否存在思考内容
            const thinkMatch = message.content.match(/<think>([\s\S]*?)<\/think>/);
            const think = thinkMatch ? thinkMatch[1].trim() : message.thinking || null;
            
            // 移除思考标签，只保留实际回答
            const answer = message.content.replace(/<think>[\s\S]*?<\/think>/, '').trim();
            
            return { think, answer };
        },

        // 渲染Markdown
        renderMarkdown(text) {
            if (!text) return '';
            try {
                return md.render(text);
            } catch (error) {
                console.error('Markdown渲染错误:', error);
                return text;
            }
        },

        // 格式化时间
        formatTime(date) {
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            return `${hours}:${minutes}`;
        },

        // 处理Enter键按下
        handleEnterPress(event) {
            // 如果按下Shift+Enter，允许换行
            if (event.shiftKey) {
                return;
            }
            // 单独按Enter发送消息
            event.preventDefault();
            this.sendMessage();
        },

        // 切换联网搜索功能
        toggleWebSearch() {
            this.webSearchActive = !this.webSearchActive;
            if (this.webSearchActive) {
                this.$message.success('已启用联网搜索功能');
            } else {
                this.$message.info('已关闭联网搜索功能');
            }
        },

        // 切换知识库功能
        toggleKnowledgeBase() {
            this.knowledgeBase = !this.knowledgeBase;
            if (!this.knowledgeBase && !this.online) {
                this.citation = false;
            }
            if (this.knowledgeBase) {
                this.$message.success('已启用知识库功能');
            } else {
                this.$message.info('已关闭知识库功能');
            }
        },

        // 切换联网搜索功能
        toggleOnline() {
            this.online = !this.online;
            if (!this.knowledgeBase && !this.online) {
                this.citation = false;
            }
            if (this.online) {
                this.$message.success('已启用联网搜索功能');
            } else {
                this.$message.info('已关闭联网搜索功能');
            }
        },

        // 切换引用模块功能
        toggleCitation() {
            if (this.canEnableCitation) {
                this.citation = !this.citation;
                if (this.citation) {
                    this.$message.success('已启用引用模块功能 - 将使用专门的引用API');
                } else {
                    this.$message.info('已关闭引用模块功能 - 将使用标准流式API');
                }
            } else {
                this.$message.warning('需要先启用知识库或联网搜索功能');
            }
        },

        // 切换deepseek模型功能
        toggleDeepseek() {
            this.useDeepseek = !this.useDeepseek;
            if (this.useDeepseek) {
                this.$message.success('已切换到DeepSeek模型');
            } else {
                this.$message.info('已切换到默认模型');
            }
        },

        // 初始化获取看板娘实例
        initPioInstance() {
            // 尝试获取全局pio_instance变量
            const checkInstance = () => {
                if (window.pio_instance) {
                    this.pioInstance = window.pio_instance;

                    // 保存并重新实现render方法，确保聊天窗口不受看板娘其他消息污染
                    this.originalRenderFunction = this.pioInstance.modules.render;
                    this.pioInstance.modules.render = this.customRenderHandler;

                    // 添加AI聊天按钮
                    this.addChatButton();

                    // 修改首页按钮功能，使用router进行导航
                    this.modifyHomeButton();
                } else {
                    console.log("等待看板娘实例加载...");
                    setTimeout(checkInstance, 300);
                }
            };

            // 开始检查实例
            checkInstance();
        },

        // 自定义render处理函数
        customRenderHandler(text) {
            // 调用原始方法显示文本
            this.originalRenderFunction.call(this.pioInstance.modules, text);

            // 如果当前处于AI对话模式，同步消息到聊天窗口
            if (this.isAIMessage) {
                // 如果是数组，随机选择一个文本
                if (Array.isArray(text)) {
                    const randomText = text[Math.floor(Math.random() * text.length)];
                    // 将看板娘的回复同步到聊天框
                    this.addMessage('ai', randomText);
                } else if (typeof text === 'string') {
                    // 将看板娘的回复同步到聊天框
                    this.addMessage('ai', text);
                }

                // 重置AI消息标志
                this.isAIMessage = false;
            }
        },

        // 修改首页按钮功能
        modifyHomeButton() {
            if (!this.pioInstance || !this.pioInstance.action) return;

            // 尝试获取看板娘菜单中的home按钮
            const homeButton = document.querySelector('.pio-container .pio-action .pio-home');
            if (!homeButton) return;

            // 移除原有点击事件
            const oldClick = homeButton.onclick;

            // 重新绑定点击事件，使用router导航
            homeButton.onclick = (event) => {
                event.preventDefault();

                // 根据用户角色导航到不同的首页
                try {
                    const store = JSON.parse(localStorage.getItem("store"));
                    const role = store && store.role;

                    if (role && role.indexOf('顾客') !== -1) {
                        router.push('/MallHome');
                    } else {
                        router.push('/HomePage');
                    }
                } catch (e) {
                    // 如果获取角色失败，默认导航到商城首页
                    router.push('/MallHome');
                }
            };

            // 保留鼠标悬停效果
            if (!homeButton.onmouseover) {
                homeButton.onmouseover = function () {
                    if (window.pio_instance && window.pio_instance.modules) {
                        window.pio_instance.modules.render('点击这里回到首页！');
                    }
                };
            }
        },

        // 为看板娘添加问答按钮
        addChatButton() {
            if (!this.pioInstance || !this.pioInstance.action) return;

            // 获取看板娘菜单元素
            const pioMenu = document.querySelector('.pio-container .pio-action');
            if (!pioMenu) return;

            // 检查是否已经存在聊天按钮
            let chatButton = document.querySelector('.pio-container .pio-action .pio-chat');

            // 如果没有则创建新按钮
            if (!chatButton) {
                chatButton = document.createElement('span');
                chatButton.className = 'pio-chat';
                // chatButton.innerHTML = '<svg t="1680330028297" viewBox="0 0 1024 1024" width="16" height="16"><path d="M512 12.672c-282.88 0-512 229.12-512 512s229.12 512 512 512 512-229.12 512-512-229.12-512-512-512zM320 384c-35.2 0-64-28.8-64-64s28.8-64 64-64 64 28.8 64 64-28.8 64-64 64zM512 384c-35.2 0-64-28.8-64-64s28.8-64 64-64 64 28.8 64 64-28.8 64-64 64zM704 384c-35.2 0-64-28.8-64-64s28.8-64 64-64 64 28.8 64 64-28.8 64-64 64z" fill="#67C23A"></path></svg>';

                // 为按钮添加点击事件
                chatButton.onclick = () => {
                    this.toggleChat(true);
                    // 调整聊天框位置
                    this.$nextTick(() => {
                        this.adjustChatPosition();
                    });
                };

                // 添加悬停文本提示
                chatButton.onmouseover = () => {
                    if (this.pioInstance && this.pioInstance.modules) {
                        this.pioInstance.modules.render('我是你的智能茶助手——小茶，点击开始对话~');
                    }
                };

                // 将按钮添加到菜单，放在皮肤按钮后面，关闭按钮前面
                const homeButton = document.querySelector('.pio-container .pio-action .pio-home');
                if (homeButton) {
                    pioMenu.insertBefore(chatButton, homeButton);
                } else {
                    pioMenu.appendChild(chatButton);
                }
            }
        },

        // 发送消息
        async sendMessage() {
            if (!this.userInput.trim() || this.isProcessing) return;

            // 设置处理标志
            this.isProcessing = true;
            
            // 添加用户消息到聊天记录
            this.addMessage('user', this.userInput);

            // 处理用户输入
            const question = this.userInput.trim();
            
            // 清空输入框
            this.userInput = '';
            
            // 处理流式问答
            this.processStreamQuestion(question);
        },

        // 处理流式问答
        processStreamQuestion(question) {
            // 显示思考状态 - 请求发出后立即显示
            this.isThinking = true;
            this.thinkingText = '正在思考中...';

            // 创建一个空的AI消息占位
            const messageIndex = this.messages.length;
            // 初始化一个消息对象
            const initialMessage = {
                type: 'ai',
                content: '',
                thinking: '',
                time: this.formatTime(new Date()),
                citations: [],
                showCitations: false
            };
            // 添加到消息列表
            this.messages.push(initialMessage);

            // 清空缓冲区
            this.streamBuffer = '';
            this.thinkingBuffer = '';
            this.inThinkingMode = false;

            console.log('开始流式问答，参数:', {
                question: question,
                slug: this.knowledgeBaseSlug,
                online: this.online,
                knowledgeBase: this.knowledgeBase,
                citation: this.citation,
                userId: this.userId,
                useDeepseek: this.useDeepseek
            });

            // 根据是否启用引用模块选择不同的API接口
            let apiEndpoint;
            if (this.useDeepseek) {
                // DeepSeek模式
                apiEndpoint = `${aiService.baseURL || 'http://localhost:8001'}/workspace/${this.knowledgeBaseSlug}/chat/stream/deepseek`;
            } else if (this.citation) {
                // 启用引用模式 - 使用专门的引用接口
                apiEndpoint = `${aiService.baseURL || 'http://localhost:8001'}/workspace/${this.knowledgeBaseSlug}/chat/citation/stream`;
            } else {
                // 普通模式
                apiEndpoint = `${aiService.baseURL || 'http://localhost:8001'}/workspace/${this.knowledgeBaseSlug}/chat/stream`;
            }

            // 准备请求体数据 - 不再传递citation参数
            const data = {
                question,
                online: this.online,
                knowledge_base: this.knowledgeBase,
                user_id: this.userId
            };

            // 如果使用DeepSeek模型，添加citation参数
            if (this.useDeepseek) {
                data.citation = this.citation;
            }

            // 使用fetch API发送POST请求
            const controller = new AbortController();
            const { signal } = controller;

            fetch(apiEndpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
                signal
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }

                    // 获取响应的reader
                    const reader = response.body.getReader();
                    const decoder = new TextDecoder();
                    let buffer = '';
                    let receivedFirstResponse = false;

                    // 读取数据流
                    function readStream() {
                        reader.read().then(({ done, value }) => {
                            if (done) {
                                this.handleStreamComplete(messageIndex);
                                return;
                            }

                            // 解码数据
                            const chunk = decoder.decode(value, { stream: true });
                            buffer += chunk;

                            // 如果这是第一个响应，停止思考动画
                            if (!receivedFirstResponse) {
                                receivedFirstResponse = true;
                                this.isThinking = false;
                            }

                            // 处理数据行
                            const lines = buffer.split('\n\n');
                            buffer = lines.pop() || '';

                            for (const line of lines) {
                                if (line.startsWith('data: ')) {
                                    const data = line.substring(6);
                                    if (data === '[DONE]') {
                                        this.handleStreamComplete(messageIndex);
                                        return;
                                    }

                                    try {
                                        const parsedData = JSON.parse(data);
                                        this.handleStreamData(parsedData, messageIndex);
                                    } catch (e) {
                                        console.error('Error parsing stream data:', e);
                                    }
                                }
                            }

                            // 继续读取
                            readStream.call(this);
                        }).catch(error => {
                            if (error.name !== 'AbortError') {
                                console.error('Stream error:', error);
                                this.handleStreamError(error, messageIndex);
                            }
                        });
                    }

                    // 开始读取
                    readStream.call(this);
                })
                .catch(error => {
                    if (error.name !== 'AbortError') {
                        console.error('Fetch error:', error);
                        this.handleStreamError(error, messageIndex);
                    }
                });

            // 保存控制器以便外部可以中断请求
            this.currentEventSource = {
                close: () => controller.abort()
            };
        },

        // 处理流式数据
        handleStreamData(data, messageIndex) {
            console.log(data.delta);
            
            // 处理错误
            if (data.error) {
                this.$set(this.messages[messageIndex], 'content', `错误: ${data.error}`);
                this.isProcessing = false;
                this.isThinking = false;
                return;
            }

            // 处理引用信息
            if (data.citations) {
                this.citations = data.citations;
                this.$set(this.messages[messageIndex], 'citations', data.citations);
                return;
            }

            // 处理文本增量
            if (data.delta) {
                // 获取当前消息的完整副本
                const currentMessage = {...this.messages[messageIndex]};
                let needsUpdate = false;
                
                // 将增量内容添加到流缓冲区
                this.streamBuffer += data.delta;
                
                // 检查是否只接收到think标签尾部
                if (data.delta.includes('</think>') && !this.streamBuffer.includes('<think>')) {
                    // 如果之前没有收到think标签头，但收到了标签尾，
                    // 将之前的所有内容视为thinking内容
                    currentMessage.thinking = this.streamBuffer.split('</think>')[0].trim();
                    
                    // 清空之前的内容，只保留</think>之后的内容作为正式回答
                    const afterThink = this.streamBuffer.split('</think>')[1] || '';
                    currentMessage.content = afterThink.trim();
                    
                    // 更新streamBuffer，只保留</think>之后的内容
                    this.streamBuffer = '</think>' + afterThink;
                }
                // 检查完整的流缓冲区中是否包含think标签
                else if (this.streamBuffer.match(/<think>([\s\S]*?)<\/think>/)) {
                    // 从缓冲区中提取思考内容
                    const thinkMatch = this.streamBuffer.match(/<think>([\s\S]*?)<\/think>/);
                    currentMessage.thinking = thinkMatch[1].trim();
                    
                    // 从内容中移除think标签及其内容
                    currentMessage.content = this.streamBuffer.replace(/<think>[\s\S]*?<\/think>/, '');
                } else {
                    // 检查是否正在构建思考内容
                    if (this.streamBuffer.includes('<think>') && !this.streamBuffer.includes('</think>')) {
                        // 正在构建思考内容，先不显示
                        const thinkContent = this.streamBuffer.split('<think>')[1];
                        if (thinkContent) {
                            currentMessage.thinking = thinkContent.trim();
                        }
                        
                        // 显示think之前的内容
                        currentMessage.content = this.streamBuffer.split('<think>')[0];
                    } else {
                        // 没有think标签或思考内容已结束，直接显示完整内容
                        currentMessage.content = this.streamBuffer;
                    }
                }
                
                // 使用Vue的$set方法更新整个消息对象，确保视图响应式更新
                this.$set(this.messages, messageIndex, currentMessage);

                // 滚动到底部
                this.$nextTick(() => {
                    const container = this.$refs.messageContainer;
                    if (container) {
                        container.scrollTop = container.scrollHeight;
                    }
                });
            }
        },

        // 处理流式错误
        handleStreamError(error, messageIndex) {
            console.error('流式请求错误:', error);
            this.isThinking = false;
            this.isProcessing = false;
            this.messages[messageIndex].content = '抱歉，请求过程中发生错误，请稍后再试。';

            // 关闭事件源
            if (this.currentEventSource) {
                this.currentEventSource.close();
                this.currentEventSource = null;
            }
        },

        // 处理流式完成
        handleStreamComplete(messageIndex) {
            console.log('流式请求完成');
            this.isThinking = false;
            this.isProcessing = false;

            // 关闭事件源
            if (this.currentEventSource) {
                this.currentEventSource.close();
                this.currentEventSource = null;
            }
        },

        // 取消生成
        cancelGeneration() {
            if (!this.isProcessing) return;

            // 关闭当前事件源
            if (this.currentEventSource) {
                this.currentEventSource.close();
                this.currentEventSource = null;
            }

            // 调用取消API
            aiService.cancelStream(this.userId)
                .then(() => {
                    console.log('成功取消生成');
                })
                .catch(error => {
                    console.error('取消生成失败:', error);
                });

            this.isProcessing = false;
            this.isThinking = false;

            // 在最后一条消息后添加取消提示
            const lastMessage = this.messages[this.messages.length - 1];
            if (lastMessage && lastMessage.type === 'ai') {
                lastMessage.content += ' [已取消生成]';
            }
        },

        // 添加消息到聊天记录
        addMessage(type, content) {
            this.messages.push({
                type,
                content,
                thinking: '',
                time: this.formatTime(new Date()),
                citations: type === 'ai' ? this.citations : [],
                showCitations: false
            });

            // 滚动到底部
            this.$nextTick(() => {
                const container = this.$refs.messageContainer;
                if (container) {
                    container.scrollTop = container.scrollHeight;
                }
            });
        },

        // 切换聊天窗口显示状态
        toggleChat(show) {
            this.chatActive = show;
            if (show) {
                this.$nextTick(() => {
                    const container = this.$refs.messageContainer;
                    if (container) {
                        container.scrollTop = container.scrollHeight;
                    }
                    this.adjustChatPosition();
                });
            }
        },

        // 调整聊天窗口位置，靠近看板娘
        adjustChatPosition() {
            // 获取看板娘容器
            const pioContainer = document.getElementById('pio-container');
            if (!pioContainer) return;

            // 获取看板娘位置
            const pioRect = pioContainer.getBoundingClientRect();
            const isLeft = pioContainer.classList.contains('left');

            // 获取聊天容器
            const chatContainer = document.querySelector('.pio-chat-container');
            if (!chatContainer) return;

            // 设置聊天窗口的位置，始终在看板娘右侧
            if (isLeft) {
                // 如果看板娘在左侧，聊天窗口就在看板娘右侧
                chatContainer.style.left = (pioRect.right + 20) + 'px';
                chatContainer.style.right = 'auto';
            } else {
                // 如果看板娘在右侧，聊天窗口就在看板娘左侧
                chatContainer.style.right = (window.innerWidth - pioRect.left + 20) + 'px';
                chatContainer.style.left = 'auto';
            }

            // 垂直对齐
            chatContainer.style.bottom = (window.innerHeight - pioRect.bottom + 20) + 'px';
        },

        // 切换引用信息显示状态
        toggleCitations(index) {
            this.messages[index].showCitations = !this.messages[index].showCitations;
        }
    },
    beforeDestroy() {
        // 移除事件监听
        window.removeEventListener('resize', this.adjustChatPosition);

        // 恢复原始render函数
        if (this.pioInstance && this.originalRenderFunction) {
            this.pioInstance.modules.render = this.originalRenderFunction;
        }

        // 关闭任何活跃的流式请求
        if (this.currentEventSource) {
            this.currentEventSource.close();
            this.currentEventSource = null;
        }
    }
}
</script>

<style>
/* 看板娘问答按钮样式 - 使用全局样式 */
.pio-chat {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    margin: 0 5px;
    cursor: pointer;
    width: 30px;
    height: 30px;
    background-color: rgba(255, 255, 255, 0.5);
    border-radius: 50%;
}

.pio-chat:hover {
    background-color: rgba(255, 255, 255, 0.8);
}
</style>

<style scoped>
.live2d-ai-assistant {
    position: relative;
    z-index: 999;
}

.pio-chat-container {
    position: fixed;
    bottom: 100px;
    right: 20px;
    width: 400px;
    height: 550px;
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
    display: flex;
    flex-direction: column;
    overflow: hidden;
    z-index: 9998;
    /* 确保低于看板娘但高于其他元素 */
    opacity: 0;
    transform: translateX(20px);
    pointer-events: none;
    transition: all 0.3s ease;
    border: 1px solid rgba(0, 0, 0, 0.06);
}

.pio-chat-container.active {
    opacity: 1;
    transform: translateX(0);
    pointer-events: all;
}

.chat-header {
    background-color: #67C23A;
    color: white;
    padding: 12px 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.chat-title {
    display: flex;
    align-items: center;
    font-weight: 500;
    font-size: 16px;
}

.chat-title i {
    margin-right: 8px;
    font-size: 18px;
}

.close-btn {
    cursor: pointer;
    padding: 8px;
    border-radius: 50%;
    transition: background-color 0.2s;
}

.close-btn:hover {
    background-color: rgba(255, 255, 255, 0.2);
}

.chat-messages {
    flex: 1;
    padding: 16px;
    overflow-y: auto;
    background-color: #f9f9f9;
    scroll-behavior: smooth;
}

.message {
    margin-bottom: 16px;
    display: flex;
    flex-direction: column;
    animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.user-message {
    align-items: flex-end;
}

.ai-message {
    align-items: flex-start;
}

.message-content {
    position: relative;
    max-width: 85%;
    word-break: break-word;
}

.message-text {
    padding: 10px 14px;
    border-radius: 18px;
    line-height: 1.5;
    font-size: 14px;
}

.message-time {
    font-size: 11px;
    margin-top: 4px;
    opacity: 0.6;
    padding: 0 8px;
}

.user-message .message-text {
    background-color: #95d475;
    color: white;
    border-top-right-radius: 4px;
}

.user-message .message-time {
    text-align: right;
}

.ai-message .message-text {
    background-color: white;
    color: #333;
    border-top-left-radius: 4px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.chat-input-area {
    background-color: white;
    border-top: 1px solid #f0f0f0;
    padding: 10px;
}

.chat-input {
    display: flex;
    position: relative;
    margin-bottom: 10px;
}

.chat-input .el-textarea>>>.el-textarea__inner {
    border-radius: 20px;
    padding: 8px 44px 8px 14px;
    resize: none;
    border: 1px solid #dcdfe6;
    transition: all 0.2s;
    max-height: 100px;
    line-height: 1.5;
}

.chat-input .el-textarea>>>.el-textarea__inner:focus {
    border-color: #67C23A;
    box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.2);
}

.send-btn {
    position: absolute;
    right: 0px;
    bottom: 0px;
    width: 39px;
    height: 39px;
    border-radius: 50%;
    border: none;
    background-color: #67C23A;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s ease;
}

.send-btn:hover {
    background-color: #85ce61;
}

.send-btn:disabled {
    background-color: #c0c4cc;
    cursor: not-allowed;
}

.send-btn.sending {
    background-color: #85ce61;
}

.send-btn i {
    font-size: 18px;
}

.chat-tools {
    display: flex;
    justify-content: space-between;
    padding: 0 10px;
    flex-wrap: wrap;
    gap: 8px;
}

.tool-btn {
    padding: 6px 12px;
    border-radius: 16px;
    font-size: 13px;
    display: flex;
    align-items: center;
    cursor: pointer;
    color: #606266;
    transition: all 0.2s;
    background-color: #f5f7fa;
    user-select: none;
    flex: 1;
    justify-content: center;
    min-width: 80px;
}

.tool-btn:hover {
    background-color: #e4e7ed;
    color: #67C23A;
}

.tool-btn.active {
    background-color: #67C23A;
    color: white;
}

.tool-btn:disabled {
    background-color: #f0f0f0;
    color: #999;
    cursor: not-allowed;
}

.tool-btn i {
    margin-right: 4px;
    font-size: 14px;
}

.knowledge-base i {
    color: #409EFF;
}

.web-search i {
    color: #E6A23C;
}

.citation i {
    color: #F56C6C;
}

.deepseek {
    display: flex;
    width: 100%;
}

;

.deepseek i {
    color: #909399;
    color: #909399;
}

.cancel {
    width: 100%;
    justify-content: center;
    margin-top: 8px;
    background-color: #f56c6c;
    color: white;
}

.cancel:hover {
    background-color: #f78989;
    color: white;
}

.thinking-indicator {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px;
    background-color: #f9f9f9;
    border-top: 1px solid #f0f0f0;
}

.thinking-dots {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 10px;
}

.thinking-dots span {
    width: 4px;
    height: 4px;
    background-color: #67C23A;
    border-radius: 50%;
    margin: 0 2px;
    animation: thinkingDots 1.2s infinite;
}

.thinking-dots span:nth-child(2) {
    animation-delay: 0.2s;
}

.thinking-dots span:nth-child(3) {
    animation-delay: 0.4s;
}

@keyframes thinkingDots {
    0% {
        opacity: 0.2;
    }

    50% {
        opacity: 1;
    }

    100% {
        opacity: 0.2;
    }
}

.thinking-text {
    font-size: 14px;
    font-weight: 500;
    color: #67C23A;
}

/* 思考内容区域 */
.thinking-content {
    background-color: #f2f2f2;
    border-radius: 8px;
    padding: 10px;
    margin-bottom: 10px;
    font-size: 0.9em;
    color: #666;
    white-space: pre-wrap;
    overflow-wrap: break-word;
    border-left: 3px solid #ccc;
    font-style: italic;
}

.thinking-text {
    font-size: 0.9em;
    color: #666;
    white-space: pre-wrap;
    overflow-wrap: break-word;
}

/* 引用相关样式 */
.citations-container {
    margin-top: 12px;
    background-color: #f5f7fa;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.citations-header {
    padding: 8px 12px;
    display: flex;
    align-items: center;
    cursor: pointer;
    font-size: 13px;
    color: #606266;
    background-color: #ebeef5;
    transition: background-color 0.2s;
}

.citations-header:hover {
    background-color: #e4e7ed;
}

.citations-header i {
    margin-right: 6px;
    transition: transform 0.3s;
}

.citations-header i.rotated {
    transform: rotate(90deg);
}

.citations-list {
    padding: 8px;
    max-height: 300px;
    overflow-y: auto;
}

.citation-item {
    margin-bottom: 8px;
    border-radius: 6px;
}

.citation-source {
    display: flex;
    align-items: center;
    font-weight: 500;
    margin-bottom: 4px;
    color: #67C23A;
}

.citation-source i {
    margin-right: 4px;
}

.citation-title {
    margin-bottom: 4px;
    font-weight: 500;
    font-size: 14px;
}

.citation-text {
    margin-bottom: 4px;
    font-size: 12px;
    color: #606266;
    line-height: 1.4;
    max-height: 80px;
    overflow-y: auto;
    background-color: #f9f9f9;
    padding: 6px;
    border-radius: 4px;
    white-space: pre-wrap;
    word-break: break-all;
}

.citation-snippet {
    margin-bottom: 4px;
    font-size: 12px;
    color: #606266;
    line-height: 1.4;
    max-height: 80px;
    overflow-y: auto;
    background-color: #f9f9f9;
    padding: 6px;
    border-radius: 4px;
    white-space: pre-wrap;
    word-break: break-all;
}

.citation-url {
    word-break: break-all;
    color: #409eff;
    font-size: 12px;
}

.citation-url a {
    color: inherit;
    text-decoration: none;
}

.citation-url a:hover {
    text-decoration: underline;
}

/* Markdown样式 */
.message-text>>>p {
    margin: 0 0 10px;
}

.message-text>>>p:last-child {
    margin-bottom: 0;
}

.message-text>>>ul,
.message-text>>>ol {
    margin: 8px 0;
    padding-left: 20px;
}

.message-text>>>code {
    background-color: #f5f7fa;
    padding: 2px 4px;
    border-radius: 3px;
    font-family: monospace;
    font-size: 0.9em;
}

.message-text>>>pre {
    background-color: #f5f7fa;
    padding: 10px;
    border-radius: 5px;
    overflow-x: auto;
    margin: 10px 0;
}

.message-text>>>pre code {
    background-color: transparent;
    padding: 0;
}

.message-text>>>table {
    border-collapse: collapse;
    width: 100%;
    margin: 10px 0;
}

.message-text>>>th,
.message-text>>>td {
    border: 1px solid #dcdfe6;
    padding: 6px 10px;
}

.message-text>>>th {
    background-color: #f5f7fa;
}

.control-panel {
    margin-bottom: 1rem;
}

.button-group {
    display: flex;
    gap: 0.5rem;
}

.control-button {
    padding: 0.5rem 1rem;
    border: 1px solid #ccc;
    border-radius: 4px;
    background: white;
    cursor: pointer;
    transition: all 0.3s ease;
}

.control-button:hover {
    background: #f0f0f0;
}

.control-button.active {
    background: #4CAF50;
    color: white;
    border-color: #4CAF50;
}

.control-button:disabled {
    background: #f0f0f0;
    color: #999;
    cursor: not-allowed;
    border-color: #ccc;
}
</style>